<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入代理商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="liaisonMan">
        <el-input
          v-model="queryParams.liaisonMan"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['agent:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agent:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['agent:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['agent:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="agentName" />
      <el-table-column label="联系人" align="center" prop="liaisonMan" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span v-if="scope.row.status === '0'" style="color: #67C23A">正常</span>
          <span v-if="scope.row.status === '1'" style="color: #F56C6C">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-map-location"
            @click="showAreaSetDrawer(scope.row)"
            v-hasPermi="['agent:area:query']"
          >代理区域</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['agent:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['agent:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理商信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="agentName">
          <el-input v-model="form.agentName" placeholder="请输入代理商名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="liaisonMan">
          <el-input v-model="form.liaisonMan" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="province">
          <el-cascader :options="pcaTextArr()" filterable
                       v-model="codeArray" @change="handleChange" style="width: 100%" />
        </el-form-item>
        <el-form-item label="" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看/设置代理区域 -->
    <el-drawer :title="areaSetDrawerTitle" :visible.sync="areaSetDrawer"
               :before-close="closeAreaSetDrawer" :wrapperClosable="false" direction="rtl">
      <div style="margin: 10px;">
        <el-popover v-model="areaSetPopover" @hide="cancelAreaSet" title="选择代理区域" width="400" trigger="click">
          <el-cascader :options="pcaTextArr()" filterable :props="areaSetPopoverProps" :collapse-tags="true"
                       v-model="areaSetChooseData" style="width: 100%" />
          <div style="margin: 10px 0; text-align: right;">
            <el-button type="primary" size="mini" @click="saveAreaSet">确 定</el-button>
            <el-button size="mini" @click="cancelAreaSet">取 消</el-button>
          </div>
        </el-popover>
        <el-button type="primary" plain icon="el-icon-setting" @click="showAreaSetPopover"
                   size="mini" v-hasPermi="['agent:area:set']">设置区域</el-button>
      </div>

      <el-table v-loading="loading" :data="areaSetDataList" style="margin-top: 10px;">
        <el-table-column label="省" align="center" prop="province" />
        <el-table-column label="市" align="center" prop="city" />
        <el-table-column label="区" align="center" prop="area" />
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo, queryAgentArea, setAgentArea } from "@/api/business/agent";
import { pcaTextArr } from 'element-china-area-data';

export default {
  name: "AgentInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agentName: null,
        liaisonMan: null,
        phone: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        agentName: [
          { required: true, message: "代理商名称不能为空", trigger: "blur" }
        ],
        liaisonMan: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        email: [
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
      },
      codeArray: [],

      areaSetDrawer: false,
      areaSetDrawerTitle: '',
      agentInfo: {},
      allAgentAreaData: [],
      areaSetDataList: [],
      areaSetPopover: false,
      areaSetPopoverProps: {
        multiple: true,
        expandTrigger: 'hover',
      },
      areaSetChooseData: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    pcaTextArr() {
      return pcaTextArr
    },
    /** 查询代理商信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        agentId: null,
        agentName: null,
        liaisonMan: null,
        phone: null,
        email: null,
        province: null,
        city: null,
        area: null,
        address: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.codeArray = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.agentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const agentId = row.agentId || this.ids
      getInfo(agentId).then(response => {
        this.form = response.data;
        this.codeArray = [this.form.province, this.form.city, this.form.area];
        this.open = true;
        this.title = "修改代理商信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.agentId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功！");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功！");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const agentIds = row.agentId || this.ids;
      this.$modal.confirm('是否确认删除所选代理商信息？').then(function() {
        return delInfo(agentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功！");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('agent/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    handleChange(){
      switch (this.codeArray.length) {
        case 1:
          this.form.province = this.codeArray[0];
          break;
        case 2:
          this.form.province = this.codeArray[0];
          this.form.city = this.codeArray[1];
          break;
        case 3:
          this.form.province = this.codeArray[0];
          this.form.city = this.codeArray[1];
          this.form.area = this.codeArray[2];
          break;
        default:
          this.form.province = "";
          this.form.city = "";
          this.form.area = "";
          break;
      }
    },
    showAreaSetDrawer(obj){
      let that = this;
      that.loading = true;
      queryAgentArea(obj.agentId).then(response => {
        let data = response.data;
        that.loading = false;
        that.agentInfo = obj;
        that.allAgentAreaData = data;
        that.areaSetDataList = that.mergeAreasByProvinceCity(data);
        that.getEchoData();
        that.areaSetDrawerTitle = obj.agentName + "代理区域";
        that.areaSetDrawer = true;
      });
    },
    getEchoData(){
      let data = this.allAgentAreaData;
      this.areaSetChooseData = [];
      for (let i = 0; i < data.length; i++) {
        let info = data[i];
        this.areaSetChooseData.push([info.province, info.city, info.area]);
      }
    },
    closeAreaSetDrawer(){
      this.cancelAreaSet();
      this.areaSetDrawer = false;
    },

    showAreaSetPopover(){
      this.areaSetPopover = true;
    },
    cancelAreaSet(){
      this.getEchoData();
      this.areaSetPopover = false;
    },
    saveAreaSet(){
      let that = this;
      if(that.areaSetChooseData.length < 1) {
        that.$modal.msgWarning("请选择代理区域！");
        return ;
      }

      let datas = [];
      for (let i = 0; i < that.areaSetChooseData.length; i++) {
        let arr = that.areaSetChooseData[i];
        datas.push({
          province: arr[0],
          city: arr[1],
          area: arr[2],
        })
      }
      setAgentArea(that.agentInfo.agentId, datas).then(response => {
        that.$modal.msgSuccess("代理区域设置成功！");
        that.showAreaSetDrawer(that.agentInfo);
        that.cancelAreaSet();
      });
    },
    mergeAreasByProvinceCity(arr) {
      const result = arr.reduce((acc, current) => {
        const key = `${current.province}-${current.city}`;
        if (!acc[key]) {
          acc[key] = { ...current, area: current.area };
        } else {
          acc[key].area = `${acc[key].area}、${current.area}`;
        }
        return acc;
      }, {});
      return Object.values(result);
    }

  }
};
</script>
<style>
.el-drawer__header {
  padding-bottom: 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #eee;
}
</style>
